package com.bizframework.core.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

	public static String DateToString(Date date) {
		if (date == null) {
			return "";
		}
		DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
		return formatDate.format(date);
	}

	public static String DateTimeToString(Date date) {
		if (date == null) {
			return "";
		}
		DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatDate.format(date);
	}

	public static String DateToString(Date date, String formatString) {
		if (date == null) {
			return "";
		}
		DateFormat formatDate = new SimpleDateFormat(formatString);
		return formatDate.format(date);
	}

	public static Date StringToDate(String dateString) throws Exception {
		return org.apache.commons.lang.time.DateUtils.parseDate(dateString,
				new String[] { "yyyy-MM-dd" });
	}

	public static Date StringToDateTime(String dateString) throws Exception {
		return org.apache.commons.lang.time.DateUtils.parseDate(dateString,
				new String[] { "yyyy-MM-dd HH:mm:ss" });
	}

	public static Date StringToDateTime(String dateString, String formatString)
			throws Exception {
		return org.apache.commons.lang.time.DateUtils.parseDate(dateString,
				new String[] { formatString });
	}

	public static int YearsBetween(Date endDate, Date startDate) {
		return (int) ((endDate.getTime() - startDate.getTime()) / (60l * 60l * 24l * 365l * 1000));
	}

	public static int DaysBetween(Date endDate, Date startDate) {
		return (int) ((endDate.getTime() - startDate.getTime()) / (1000l * 60l * 60l * 24l));
	}

	public static int HoursBetween(Date endDate, Date startDate) {
		return (int) ((endDate.getTime() - startDate.getTime()) / (1000l * 60l * 60l));
	}

	@SuppressWarnings("deprecation")
	public static boolean isNullDate(Date date) {
		return (date == null || date.getTime() == new Date(0, 0, 0).getTime());
	}

	public static int getYear(Date date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		return ca.get(Calendar.YEAR);
	}
	
	public static int getMonth(Date date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		return ca.get(Calendar.MONTH) + 1;
	}
	
	public static int getDayOfMonth(Date date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		return ca.get(Calendar.DAY_OF_MONTH);
	}
	
	public static int getHour(Date date) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		return ca.get(Calendar.HOUR_OF_DAY);
	}
}
